package org.usmile.algorithms.learn.sort;

import java.util.Arrays;

/**
 * 计数排序
 */
@SuppressWarnings("all")
public class CountSorter {
    public void sort(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return;
        }
        int max = nums[0];
        int min = nums[0];
        for (int i = 1; i < nums.length; i++) {
            max = Math.max(max, nums[i]);
            min = Math.min(min, nums[i]);
        }

        int[] count = new int[max - min + 1];
        for (int num : nums) {
            count[num - min]++;
        }
        for (int i = 1; i < count.length; i++) {
            count[i] += count[i - 1];
        }

        int[] temp = new int[nums.length];
        for (int i = nums.length - 1; i >= 0; i--) {
            temp[count[nums[i] - min]-- - 1] = nums[i];
        }

        for (int i = 0; i < nums.length; i++) {
            nums[i] = temp[i];
        }
    }

    public static void main(String[] args) {
        CountSorter sorter = new CountSorter();
        int[] data = {4, 2, -2, 8, 3, 3, 1};
        sorter.sort(data);
        System.out.println(Arrays.toString(data));
    }
}
